using System;
using System.Diagnostics;
using System.IO;

/// <summary>
///LaunchCmd can be used to run a command line exe from within managed code
///  - set to act as an automation object
///  - returns string output to command line, if any
/// </summary>

namespace Commerce.Common
{
    public class LaunchCmd
    {
        public static string Run(string exeName, string argsLine, int timeoutSeconds)
        {
            StreamReader outputStream = StreamReader.Null;
            string output = "";
            bool success = false;

            try
            {
                Process newProcess = new Process();
                newProcess.StartInfo.FileName = exeName;
                newProcess.StartInfo.Arguments = argsLine;
                newProcess.StartInfo.UseShellExecute = false;
                newProcess.StartInfo.CreateNoWindow = true;
                newProcess.StartInfo.RedirectStandardOutput = true;
                newProcess.Start();

                if (0 == timeoutSeconds)
                {
                    outputStream = newProcess.StandardOutput;
                    output = outputStream.ReadToEnd();
                    newProcess.WaitForExit();
                }
                else
                {
                    success = newProcess.WaitForExit(timeoutSeconds * 1000);
                }

                if (success)
                {
                    outputStream = newProcess.StandardOutput;
                    output = outputStream.ReadToEnd();
                }
                else
                {
                    output = "Timed out at " + timeoutSeconds + " seconds waiting for " + exeName + " to exit.";
                }
            }

            catch (Exception e)
            {   
                // PVS - just let this go, it'll get picked up next time
                //throw (new Exception("An error occurred running " + exeName + ".", e));
            }
            finally
            {
                outputStream.Close();
            }

            return "\t" + output;

        }
    }
}


